package cn.itsource.ymcc.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.itsource.ymcc.common.constant.BusinessKey;
import cn.itsource.ymcc.common.exception.GlobalException;
import cn.itsource.ymcc.common.result.JsonResult;
import cn.itsource.ymcc.common.util.AssertUtil;
import cn.itsource.ymcc.common.util.StrUtils;
import cn.itsource.ymcc.dto.UserRegistDto;
import cn.itsource.ymcc.service.IVerifycodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public JsonResult imageCode(String key) {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(300, 100, 4, 4);
        String code = captcha.getCode();//存放redis
        redisTemplate.opsForValue().set(key,code, 3,TimeUnit.MINUTES);
        String imageBase64 = captcha.getImageBase64();
        return JsonResult.success().setData(imageBase64);
    }

    @Override
    public JsonResult sendSmsCode(UserRegistDto userRegistDto) {
        AssertUtil.isTrue(redisTemplate.hasKey(userRegistDto.getKey()),"图片验证码已过期");

        String code = redisTemplate.opsForValue().get(userRegistDto.getKey()).toString();
        AssertUtil.isTrue(code.equalsIgnoreCase(userRegistDto.getCode()),"图片验证码不匹配");

        //发送短信
        String smsCode = StrUtils.getRandomString(6);
        String smsKey = userRegistDto.getPhone()+ BusinessKey.SEGMENTATION+BusinessKey.REGISTER_SMS_CODE_SUFFIX;
        if(redisTemplate.hasKey(smsKey)){
            Long expire = redisTemplate.getExpire(smsKey,TimeUnit.SECONDS);//到记时
            if(expire>120){
                throw new GlobalException("你太快了");
            }else {
                String string = redisTemplate.opsForValue().get(smsKey).toString();
                smsCode = string;
            }
        }
        //存放redis
        redisTemplate.opsForValue().set(smsKey,smsCode,3,TimeUnit.MINUTES);
        System.out.println(smsCode); //调用工具类发送短信
        return JsonResult.success();
    }
}
